package org.springframework.context.annotation;

import lombok.Data;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static com.google.common.base.Preconditions.checkArgument;

@Data
public class ConfigurationClassPostProcessor {
    private ConfigurationClassBeanDefinitionReader reader;
    private final Set<Integer> registriesPostProcessed = new HashSet<>();
    private final Set<Integer> factoriesPostProcessed = new HashSet<>();

    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
        int registryId = System.identityHashCode(registry);
        checkArgument(this.registriesPostProcessed.add(registryId), "postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
        checkArgument(this.factoriesPostProcessed.add(registryId), "postProcessBeanFactory already called on this post-processor against " + registry);
        processConfigBeanDefinitions(registry);
    }

    public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
        Map<String, BeanDefinition> bootstrapBeanDefinitionMap = registry.getBootstrapBeanDefinitionMap();
        Set<BeanDefinitionHolder> candidates = bootstrapBeanDefinitionMap
                .entrySet()
                .stream()
                .map(entry -> BeanDefinitionHolder.builder().beanDefinition(entry.getValue()).beanName(entry.getKey()).build())
                .collect(Collectors.toSet());

        ConfigurationClassParser parser = ConfigurationClassParser.builder().registry(registry).build();
        parser.parse(candidates);
        Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
//        this.reader.loadBeanDefinitions(configClasses);

    }
}
